const fs=require('fs');
const path=require('path');
const http=require('http');
const argv=process.argv[2];

http.createServer((req,res)=>{
    res.writeHead(200,{'Content-Type':'text/plain;charset=utf-8'});
    if(argv){
        var inputPath=path.join(__dirname,'/'+argv);
        if(fs.existsSync(inputPath)){
            var fileObj=fs.statSync(inputPath);
            if(fileObj.isFile()){
                var fd=fs.openSync(inputPath);
                fs.read(fd,(err,bytesRead,buffer)=>{
                    console.log(bytesRead);
                    if(err){
                        console.log(err);
                    }else{
                        res.end(buffer.slice(0,bytesRead).toString('utf-8'));
                    }
                })
                //fs.close(fd);
            }else{
                console.log("不能读取文件夹");
            }
        }else{
            console.log("该文件路径不存在");
        }
    }else{
        var currentPath=__filename;
        var fd=fs.openSync(currentPath,'r');
        fs.read(fd,(err,bytesRead,buffer)=>{
            if(err){
                console.log(err);
            }else{
                res.end(buffer.slice(0,bytesRead).toString('utf-8'));
            }
        });
        fs.close(fd);
    }
}).listen(8081);